/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package newpackage;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Ruchlis
 */
public class ChatAdministration {
    private List<ConnectionHandler> chatClients = new ArrayList<ConnectionHandler>();
    private List<String> messageList = new ArrayList<String>();
    
    public void addUser(ConnectionHandler handle)
    {
        chatClients.add(handle);
    }
    
    public synchronized void notifyDiscconection(ConnectionHandler leaving){
        chatClients.remove(leaving);
        sendGenericMessage("Unfortunately " + leaving.getUsername() + " had left the building.");
    }
    
    public synchronized void sendMessage(String message, String userName)
    {
        sendGenericMessage(userName + ": " + message);
    }
    
    private void sendGenericMessage(String message)
    {
        for(int i = 0 ; i < chatClients.size() ; i++)
        {
            ConnectionHandler client = null;
            try{
                client = chatClients.get(i);
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(client.getSocket().getOutputStream())); 
                writer.println(message);
                writer.flush();
            }
            catch(IOException ex)
            {
                if(client != null){
                    notifyDiscconection(client);
                    i--;
                }    
            }
        }
    }
}
